package com.kehutong.common;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class UrlUtils {
	
	private static final String CHAT_ENCODING = "UTF-8";

	/**
	 * 解析url参数
	 * 
	 * @param url
	 * @return
	 */
	public static Map<String, String> getQueryParams(String url) {
        int start = url.indexOf('?');
        String paramStr = url.substring(start, url.length()).trim();
        if (paramStr == null || paramStr.isEmpty()) {
        	return Collections.emptyMap();
        }
        
        Map<String, String> params = new HashMap<String, String>();
      
        int equals;
        String key;
        String value;
        while (start != -1) {
            // read parameter name
            equals = url.indexOf('=', start);
            if (equals != -1) {
                key = url.substring(start + 1, equals);
            } else {
                key = url.substring(start + 1);
            }
 
            // read parameter value
            value = "";
            if (equals != -1) {
                start = url.indexOf('&', equals);
                if (start != -1) {
                    value = url.substring(equals + 1, start);
                } else {
                    value = url.substring(equals + 1);
                }
            }
 
            params.put(urlDecoder(key), urlDecoder(value));
        }
 
        return params;
    }
	
	public static String urlDecoder(String url) {
		try {
			return URLDecoder.decode(url, CHAT_ENCODING);
		} catch (UnsupportedEncodingException e) {
			return url;
		}
	}
	
	public static String urlEncode(String url) {
		try {
			return URLDecoder.decode(url, CHAT_ENCODING);
		} catch (UnsupportedEncodingException e) {
			return url;
		}
	}
	
}
